document.addEventListener('DOMContentLoaded', function() {
  const roomsList = document.querySelectorAll('ul li');
  const chatWindowsContainer = document.getElementById('chat-windows');

  let activeRoom = null;

  function createChatWindow(roomName) {
    const chatWindow = document.createElement('div');
    chatWindow.classList.add('chat-window');
    chatWindow.dataset.room = roomName;

    const messagesContainer = document.createElement('ul');
    messagesContainer.id = `messages-${roomName}`;
    chatWindow.appendChild(messagesContainer);

    const inputContainer = document.createElement('div');
    const chatInput = document.createElement('input');
    chatInput.type = 'text';
    chatInput.placeholder = `在 ${roomName} 中输入消息...`;
    const sendButton = document.createElement('button');
    sendButton.textContent = '发送';

    inputContainer.appendChild(chatInput);
    inputContainer.appendChild(sendButton);
    chatWindow.appendChild(inputContainer);

    sendButton.addEventListener('click', function() {
      const message = chatInput.value.trim();
      if (message) {
        const messageItem = document.createElement('li');
        messageItem.textContent = message;
        messagesContainer.appendChild(messageItem);
        chatInput.value = '';
      }
    });

    chatWindowsContainer.appendChild(chatWindow);
  }

  roomsList.forEach(room => {
    room.addEventListener('click', function() {
      // 隐藏所有聊天窗口
      const chatWindows = document.querySelectorAll('.chat-window');
      chatWindows.forEach(window => window.classList.remove('active'));

      // 找到点击的房间并显示聊天窗口
      const roomName = this.dataset.room;
      const existingChatWindow = document.querySelector(`.chat-window[data-room="${roomName}"]`);
      if (existingChatWindow) {
        existingChatWindow.classList.add('active');
        activeRoom = existingChatWindow;
      } else {
        createChatWindow(roomName);
        activeRoom = chatWindowsContainer.lastChild;
        activeRoom.classList.add('active');
      }
    });
  });
});